package com.example.ecs.systems.physics;

import com.example.ecs.components.PositionComponent;
import com.example.ecs.components.VelocityComponent;
import com.example.ecs.components.physics.BoundaryComponent;
import com.example.ecs.core.Entity;
import com.example.ecs.core.System;

/**
 * BoundarySystem类负责处理实体与边界的碰撞检测
 */
public class BoundarySystem extends System {
    private int screenWidth;
    private int screenHeight;
    
    public BoundarySystem(int screenWidth, int screenHeight) {
        super();
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
    }
    
    @Override
    public void update(double deltaTime) {
        for (Entity entity : entities) {
            if (entity.hasComponent(PositionComponent.class) &&
                entity.hasComponent(VelocityComponent.class) &&
                entity.hasComponent(BoundaryComponent.class)) {
                
                PositionComponent position = entity.getComponent(PositionComponent.class);
                VelocityComponent velocity = entity.getComponent(VelocityComponent.class);
                BoundaryComponent boundary = entity.getComponent(BoundaryComponent.class);
                
                // 检查是否与边界碰撞
                if (boundary.bounceOnCollision) {
                    // 检查左边界
                    if (position.x <= boundary.minX) {
                        position.x = boundary.minX;
                        velocity.vx = Math.abs(velocity.vx); // 取反X速度
                    }
                    // 检查右边界
                    else if (position.x >= boundary.maxX) {
                        position.x = boundary.maxX;
                        velocity.vx = -Math.abs(velocity.vx); // 取反X速度
                    }
                    
                    // 检查上边界
                    if (position.y <= boundary.minY) {
                        position.y = boundary.minY;
                        velocity.vy = Math.abs(velocity.vy); // 取反Y速度
                    }
                    // 检查下边界
                    else if (position.y >= boundary.maxY) {
                        position.y = boundary.maxY;
                        velocity.vy = -Math.abs(velocity.vy); // 取反Y速度
                    }
                }
            }
        }
    }
    
    public void setScreenSize(int width, int height) {
        this.screenWidth = width;
        this.screenHeight = height;
    }
}